// Автосаджест городов
$('.route-search').livequery(function() {
	RouteSearch.init();
	$( ".city-field" ).autocomplete({
		source: function( request, response ) {
			$.ajax({
				url: W_AJAX + 'city/get',
						dataType: "jsonp",
						type : 'POST',
						data: {
							nameStartWith: request.term
						},
						success: function( data ) {
							response( $.map( data.citiesNames, function( item ) {
								return {
									label: item.city_name,
									value: item.city_name,
									id: item.ID_city
								}
							}));
						}
			});
		},
		minLength: 2,
		select: function( event, ui ) {
			$(this).next().val(ui.item.id);
		},
		change: function( event, ui ) {
		}
	});
});

var RouteSearch = {
		showType : 'like',
		likeOrdersArr : [],
		sameOrdersArr : [],
		busyFlag : false,
		
		init : function() {
			routeMap.init();
			$('.from').focus();
			var self = this;
			$('#s-route').submit(function() {
				if($('.from').val() != '' && $('.to').val() != '' && !self.busyFlag) {
					self.busyFlag = true;
					$('.results').slideUp();
					self.clearResults();
					$.ajax({
						url: W_AJAX + 'order/get-route-orders',
						dataType: "jsonp",
						type : 'POST',
						data: {
							from: $('.from').val(),
							to: $('.to').val()
						},
						success: function(data) {
							if(data.status == 'OK') self.resultsHeandler(data);
							else if(data.result == 'error' && data.error == 'NOT_FOUND') alert('Невозможно найти схожие заказы для заданных городов.');
							self.busyFlag = false;
						}
					});
				}
				
				$('.type_handler div').bind('mouseenter mouseleave click mousedown',function(e) {
					if(!$(this).hasClass('active')) {
						if(e.type == 'mouseenter') $(this).addClass('hover');
						else if(e.type == 'mouseleave')  $(this).removeClass('hover');
						else {
							$('.type_handler .active').removeClass('active');
							if($(this).hasClass('same')) {
								$(this).addClass('active').removeClass('hover');
								self.showType = 'same';
								self.showOrders();
							}
							if($(this).hasClass('like')) {
								$(this).addClass('active').removeClass('hover');
								self.showType = 'like';
								self.showOrders();
							}	
						}
					}
					return false;
				});
				
				$('.orders .o-item').live('mouseenter mouseleave click mousedown', function(e) {
					if(!$(this).hasClass('active')) {
						if(e.type == 'click') {
							showItem($(this));
						}
						if(e.type == 'mouseenter') $(this).addClass('hover');
					}
					else if(e.type == 'click') hideItem($(this));
					if(e.type == 'mouseleave') $(this).removeClass('hover');
					
					return false;
				});
				
				function showItem(item) {
					var addInf = item.children('.add-inf');
					addInf.slideDown(100, function(){$('.add-inf').clearQueue(); item.addClass('active')});
				}
				
				function hideItem(item) {
					var addInf = item.children('.add-inf');
					addInf.slideUp(100, function(){$('.add-inf').clearQueue(); item.removeClass('active')});
				}
				
				$('.type_handler .same').click();

				return false;
			});
		},
		
		resultsHeandler : function (data) {
			var self = this;
			self.likeOrdersArr = [];
			self.sameOrdersArr = [];
			self.markers = data.markersArray;
			routeMap.dropMarkers(self.markers);
			
			var indexArr = [];
			var routeDistance = 0;
			var lastIndex = self.markers.length - 1;
			for(i in self.markers) {
				routeDistance += parseInt(self.markers[i].distance_to_next);
				if(!self.markers[i].no_on_map && i != 0 && i != lastIndex) indexArr.push({city_type: self.markers[i].city_type, index: parseInt(i)});
			}
			
			var minDistance =  Math.ceil(6371 * Math.acos(Math.sin(data.markersArray[0].latitude * Math.PI / 180) * Math.sin(data.markersArray[i].latitude * Math.PI / 180) + Math.cos(data.markersArray[0].latitude * Math.PI / 180) * Math.cos(data.markersArray[i].latitude * Math.PI / 180) * Math.cos(data.markersArray[0].longitude * Math.PI / 180 - data.markersArray[i].longitude * Math.PI / 180)));

			indexArr.sort(biggestSort);
			indexArr.splice(5, indexArr.length);
			indexArr.sort(indexSort);
			
			
			function biggestSort(i, ii) {
				if (i.city_type > ii.city_type)
			        return -1;
			    else if (i.city_type < ii.city_type)
			        return 1;
			    else
			        return 0;
			}
			
			function indexSort(i, ii) {
				if (i.index > ii.index)
			        return 1;
			    else if (i.index < ii.index)
			        return -1;
			    else
			        return 0;
			}
			
			self.makeOrdersLists(data.orders);
			self.showInfo(routeDistance, minDistance, data.isCompositive, indexArr);
			self.showResults();
		},
		
		showResults : function () {
			var self = this;
			self.showOrders();
			$('.results').slideDown();
		},
		
		makeOrdersLists : function(ordersArray) {
			var self = this;
			for(i in ordersArray) {
				if(ordersArray[i].distance_difference == null)  self.makeSameOrderItem(ordersArray[i]);
				else self.makeLikeOrderItem(ordersArray[i]);
			}	
		},
		
		makeSameOrderItem : function(orderArr) {
			var self = this;
			var item = '';
			item += '<div class="o-item">';
			item += '<div class="short-inf"><div class="o-desc">' + (orderArr.description ? orderArr.description : '')  + '</div><div class="cost">' + (orderArr.price ? orderArr.price : '-') + '</div><div class="date">' + getDate(orderArr.date) + '</div>' + self.clearBlock() + '</div>';
			if(orderArr.is_fin) item += '<div class="add-inf">' + self.addInfItemwrap('откуда', orderArr.place_start) + self.addInfItemwrap('куда', orderArr.place_finish) + self.addInfItemwrap('цена за час', orderArr.price_hour) +'</div>';
			else item += '<div class="add-inf">' + self.addInfItemwrap('телефон', orderArr.one_phone) +'</div>';
			item += '</div>';
			
			self.sameOrdersArr.push(item);
		},
		
		makeLikeOrderItem : function(orderArr) {
			var self = this;
			var item = '';
			item += '<div class="o-item">';
			item += '<div class="short-inf"><div class="from">' + orderArr.from + '</div><div class="to">' + orderArr.to + '</div><div class="cost">' + orderArr.price + '</div><div class="dist">' + orderArr.distance + '</div><div class="dist_diff">' + orderArr.distance_difference + '</div>' + self.clearBlock() + '</div>';
			item += '<div class="add-inf">' + self.addInfItemwrap('откуда', orderArr.place_start) + self.addInfItemwrap('куда', orderArr.place_finish) + self.addInfItemwrap('дата', getDate(orderArr.date)) + self.addInfItemwrap('цена за час', orderArr.price_hour) +'</div>';
			item += '</div>';
			
			self.likeOrdersArr.push(item);
		},
		
		showOrders : function() {
			var self = this;
			var arrToShow = [];
			var string = '';
			if(self.showType == 'same') {
				arrToShow = self.sameOrdersArr;
				string = '<div class="top"><div class="o-desc">Описание</div><div class="cost">Стоимость</div><div class="date">Дата</div>' +  self.clearBlock() + '</div>';
			}
			else if(self.showType == 'like') {
				arrToShow = self.likeOrdersArr;
				string = '<div class="top"><div class="from">Откуда</div><div class="to">Куда</div><div class="cost">Стоимость</div><div class="dist">Расстояние</div><div class="dist_diff">Отличие</div>' + self.clearBlock() + '</div>';
			}
			
			self.clearResults();
			
			if(!arrToShow.length) {
				$('.results .orders').append('<div class="inf">Заказы отсутствуют</div>');
				return false;
			}
			
			for(i in arrToShow) {
				string += arrToShow[i];
			}
			
			$('.results .orders').append(string);
		},
		
		showInfo : function(routeDistance, minDistance, isCompositive, indexArr) {
			var self = this;
			$('.results .desc').html('');
			if(isCompositive) $('.results .desc').append('<div class="alert">Внимание! Маршрута нет в БД - данные приблизительные.</div>');
			$('.results .desc').append('<p>МАРШРУТ - <span>  ' + routeDistance +' КМ</span></p><p>ПО ПРЯМОЙ - <span>' + minDistance  + ' КМ</span></p>');
			
			var string = '';
			for(var i in indexArr) {
				string += (i != 0 ? ', ' : '') + self.markers[indexArr[i].index].city_name;
			}
			
			$('.results .desc').append('<p>НА ПУТИ: <span class="lit">' + string + '</span></p>');
		},
		
		clearResults : function() {
			$('.results .orders').html('');
		},
		
		clearBlock : function() {
			return '<div class="clear"></div>';
		},
		
		addInfItemwrap : function(name, value) {
			return '<div><span>' + name + ': </span>' + value + '</div>';
		}
}